/*
 * Created on Jan 12, 2009
 */
package ak.salmon.model;

import java.awt.Point;
import java.util.List;


public abstract class NodeGroup implements DrawingElement {

    protected int width;
    protected int height;
    protected int childrenWidth;
    protected int childrenHeight;

    protected final Node parent;
    protected final List<DrawingElement> children;

    protected Point absolutePosition;
    protected Point relativePosition = new Point(0, 0);

    public NodeGroup(Node parent, List<DrawingElement> children) {
        this.parent = parent;
        this.children = children;
    }

    @Override
    public final void position(Point groupRef) {
        this.absolutePosition = groupRef;
        parent.position(add(groupRef, parent.getRelativePosition()));
        for (DrawingElement child : children) {
            child.position(add(groupRef, child.getRelativePosition()));
        }

        // realign parent position with child if there's only 1 direct child
        if (children.size() == 1) {
            Point topHub = children.get(0).getTopHub();
            Point botHub = parent.getBottomHub();

            parent.getRelativePosition().x -= (botHub.x - topHub.x);
            parent.position(add(groupRef, parent.getRelativePosition()));
        }
    }

    protected static Point add(Point reference, Point relative) {
        return new Point(reference.x + relative.x, reference.y + relative.y);
    }

    @Override
    public final Point getTopHub() {
        return parent.getTopHub();
    }

    @Override
    public final Point getLeftHub() {
        return parent.getLeftHub();
    }

    @Override
    public final Point getRightHub() {
        return parent.getRightHub();
    }

    @Override
    public final Point getBottomHub() {
        return parent.getBottomHub();
    }

    @Override
    public final int getWidth() {
        if (children.size() == 0) return parent.getWidth();
        return width;
    }

    @Override
    public final int getHeight() {
        if (children.size() == 0) return parent.getHeight();
        return height;
    }

    @Override
    public final int getChildrenWidth() {
        if (children.size() == 0) return 0;
        return childrenWidth;
    }

    @Override
    public final int getChildrenHeight() {
        if (children.size() == 0) return 0;
        return childrenHeight;
    }

    @Override
    public Point getRelativePosition() {
        return relativePosition;
    }

    @Override
    public void setRelativePosition(Point relativePosition) {
        this.relativePosition = relativePosition;
    }
}
